package top.kaoshanji.q1ch03a.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.kaoshanji.q1ch03a.dao.LoginLogDao;
import top.kaoshanji.q1ch03a.dao.UserDao;
import top.kaoshanji.q1ch03a.domain.LoginLog;
import top.kaoshanji.q1ch03a.domain.User;

/**
 * @author kaoshanji
 * ^_^
 * create time 2025/5/3 18:10
 */
@Service
public class UserService {

    private UserDao userDao;
    private LoginLogDao loginLogDao;

    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Autowired
    public void setLoginLogDao(LoginLogDao loginLogDao) {
        this.loginLogDao = loginLogDao;
    }

    /**
     * 判断用户名与命名是否匹配
     * @param userName userName
     * @param password password
     * @return boolean
     */
    public boolean hasMatchUser(String userName, String password) {
        int matchCount = userDao.getMatchCount(userName, password);
        return matchCount > 0;
    }

    /**
     * 查询用户信息
     * @param userName userName
     * @return User
     */
    public User findUserByUserName(String userName) {
        return userDao.findUserByUserName(userName);
    }

    @Transactional
    public void loginSuccess(User user) {

        LoginLog loginLog = new LoginLog();
        loginLog.setUserId(user.getUserId());
        loginLog.setIp(user.getLastIp());
        loginLog.setLoginDate(user.getLastVisit());

        user.setCredits(user.getCredits() + 5);

        userDao.updateLoginInfo(user);
        loginLogDao.insertLoginLog(loginLog);
    }


}
